/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.darren.euc.entity.HaqiDTO;
import com.darren.euc.entity.HaqiRecord;
import com.darren.euc.entity.Member;
import com.darren.euc.repository.HaqiRecordRepository;
import com.darren.euc.repository.MemberRepository;
import com.darren.euc.service.ClientParamsEntityService;
import com.darren.euc.util.DateUtil;
import com.darren.euc.util.PropertyConfigurer;
import com.darren.euc.util.StringUtil;
import com.darren.euc.util.haqi.HaquAPIHandler;
import com.darren.euc.util.haqi.request.WorkFindRequest;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 在这里编写类的功能描述
 *
 * @author fangwenhao
 * @created 2018/4/5
 */
@Component
public class HaqiTask {

    @Autowired
    private HaqiRecordRepository haqiRecordRepository;

    @Autowired
    private ClientParamsEntityService clientParamsEntityService;

    @Autowired
    private MemberRepository memberRepository;

    /**
     * 定期更新当天数据，每天 09:50:59 13:50:59 19:50:59 23:50:59 执行一次
     */
    @Scheduled(cron = "59 50 9,13,20,23 * * ?")
    public void syncCurrHaqiRecord() {
        syncCurrHaqiRecord(new DateTime().toString("yyyy-MM-dd"));
    }

    public void syncCurrHaqiRecord(String time) {
        int index = 1;
        String result = requsetRecords(index,time);
        JSONObject jsonObject =JSONObject.parseObject(result).getJSONObject("data");
        JSONArray content = jsonObject.getJSONArray("content");
        aoe(content);
        Boolean last = jsonObject.getBoolean("last");
        while (!last){
            result = requsetRecords(++index,time);
            jsonObject =JSONObject.parseObject(result).getJSONObject("data");
            content = jsonObject.getJSONArray("content");
            aoe(content);
            last = jsonObject.getBoolean("last");
        }
    }

    private String requsetRecords(int index, String time){
        WorkFindRequest requestParams = new WorkFindRequest();
        requestParams.setStart(time);
        requestParams.setEnd(time);
        requestParams.setIndex(index);
        requestParams.setSize(20);
        requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        return HaquAPIHandler.getWorkFind(requestParams);
    }

    private void aoe(JSONArray content) {
        if (content.isEmpty()){
            return;
        }
        List<HaqiDTO> haqiDTOList = JSONArray.parseArray(content.toString(),HaqiDTO.class);
        for (HaqiDTO haqiDTO : haqiDTOList){
            Date checkOutTime = null;
            Integer status2 = 0;// 异常
            if (!StringUtil.isEmptyOrWhitespace(haqiDTO.getCheckOutTime())){
                checkOutTime = DateUtil.string2Date(haqiDTO.getCheckOutTime(),"yyyy-MM-dd HH:mm:ss");
                status2 = judgeInJobTime(haqiDTO.getCheckOutTime(),haqiDTO.getFaceUserId());
            }
            BigDecimal workTime = haqiDTO.getWorkTime();
            Long faceUserId = haqiDTO.getFaceUserId();
            Long recordId = haqiDTO.getId();
            Date checkDate = DateUtil.string2Date(haqiDTO.getDate(),"yyyy-MM-dd");
            Integer num = haqiRecordRepository.updateHaqiRecord(checkOutTime,workTime,status2,faceUserId,recordId,checkDate);
            if (num == 0){
                HaqiRecord haqiRecord = new HaqiRecord();
                haqiRecord.setRecordId(haqiDTO.getId());
                haqiRecord.setAppId(haqiDTO.getAppId());
                haqiRecord.setFaceUserId(haqiDTO.getFaceUserId());
                haqiRecord.setUserName(haqiDTO.getUserName());
                haqiRecord.setCheckDevice(haqiDTO.getCheckDevice());
                haqiRecord.setCheckDate(DateUtil.string2Date(haqiDTO.getDate(),"yyyy-MM-dd"));
                haqiRecord.setCheckInTime(DateUtil.string2Date(haqiDTO.getCheckInTime(),"yyyy-MM-dd HH:mm:ss"));
                haqiRecord.setStatus2(0);
                if (!StringUtil.isEmptyOrWhitespace(haqiDTO.getCheckOutTime())){
                    checkOutTime = DateUtil.string2Date(haqiDTO.getCheckOutTime(),"yyyy-MM-dd HH:mm:ss");
                    status2 = judgeInJobTime(haqiDTO.getCheckOutTime(),haqiDTO.getFaceUserId());
                    haqiRecord.setCheckOutTime(checkOutTime);
                    haqiRecord.setStatus2(status2);
                }
                haqiRecord.setStatus1(judgeInJobTime(haqiDTO.getCheckInTime(),haqiRecord.getFaceUserId()));
                haqiRecord.setAddTime(new Date());
                haqiRecord.setModTime(new Date());
                haqiRecord.setWorkTime(haqiDTO.getWorkTime());
                haqiRecordRepository.save(haqiRecord);
            }
        }
    }

    // 首打
    private Integer judgeInJobTime(String time, Long faceUserId){
        Member member = memberRepository.findByFaceUserId(faceUserId);
        try {
            Boolean bool = clientParamsEntityService.judgeInJobTime(time.substring(11),member.getClientId());
            if (bool){
                return 0;
            }else {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
